<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-button class="filter-item" :type="all" @click="handleFilter(undefined)">全部</el-button> -->
      <el-button class="filter-item" :type="waiting" @click="handleFilter(0)">待审核</el-button>
      <el-button class="filter-item" :type="approval" @click="handleFilter(1)">已批准</el-button>
      <el-button class="filter-item" :type="rejected" @click="handleFilter(2)">已驳回</el-button>
    </div>
    <div class="filter-container">
      <el-select v-model="listQuery.userType" clearable style="width: 200px" class="filter-item" placeholder="商户类型">
        <el-option v-for="(item, index) in levelDic" :key="item" :label="item" :value="index" />
      </el-select>
      <el-input v-model="listQuery.companyName" clearable class="filter-item" style="width: 160px;" placeholder="公司名称" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter(listQuery.approveStatus)">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            
            <el-form-item v-if="props.row.companyLogo" label="公司logo">
              <!-- <img :src="props.row.companyLogo" width="500"> -->
              <viewer >
                <img :src="props.row.companyLogo" width="500">
              </viewer>
            </el-form-item>

            <el-form-item v-if="props.row.certificatesImages" label="资质证书">
             <viewer >
               <img v-for="certificatesImage in props.row.certificatesImages" :key="certificatesImage" :src="certificatesImage" width="500" style="margin-right: 15px;">
             </viewer>  
            </el-form-item>

            <el-form-item v-if="props.row.idCard1Url" label="身份证正面图片">
              <viewer >
                <img :src="props.row.idCard1Url" width="500">
              </viewer>
            </el-form-item>

            <el-form-item v-if="props.row.idCard2Url" label="身份证反面图片">
              <viewer >
                <img :src="props.row.idCard2Url" width="500">
              </viewer> 
            </el-form-item>

          </el-form>
        </template>
      </el-table-column>
      <!-- <el-table-column
        type="selection"
        width="50"
        :selectable="selectable"
        align="center"
        fixed="left"
        :resizable="false"
      /> -->

      <el-table-column align="center" label="商户类型" prop="userType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.userType === 0 ? '' : scope.row.userType === 1 ? 'success' :  'warning' " >{{ levelDic[scope.row.userType] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="公司名称" prop="companyName" />

      <el-table-column align="center" label="联系人" prop="contactName" />

      <el-table-column align="center" label="联系人电话" prop="contactTel" />

      <el-table-column align="center" label="审核状态" prop="approveStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.approveStatus === 0 ? '' : scope.row.approveStatus === 1 ? 'success' :  'danger' " >{{ statusDic[scope.row.approveStatus] }}</el-tag>
        </template>
      </el-table-column>
      

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.approveStatus==1||!scope.row.approveStatus==2" type="primary" size="mini" @click="handleThrough(scope.row)">审核</el-button>
          <el-button v-if="scope.row.approveStatus==1||scope.row.approveStatus==2" type="primary" size="mini" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="770px">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="130px" style="width: 500px; margin-left:50px;">
        <el-form-item  label="公 司 名 称 :">
          <el-input v-if="dialogStatus=='checkPending'" v-model="dataForm.companyName" clearable maxlength="50" />
          <span v-else class="form-span">{{dataForm.companyName}}</span>
        </el-form-item>
        <el-form-item label=" 联 系 人 :">
          <el-input v-if="dialogStatus=='checkPending'" v-model="dataForm.contactName" clearable maxlength="50" />
          <span v-else class="form-span">{{dataForm.contactName}}</span>
        </el-form-item>
        <el-form-item label="联 系 人 电 话:">
          <el-input v-if="dialogStatus=='checkPending'" v-model="dataForm.contactTel" clearable maxlength="50" />
          <span v-else class="form-span">{{dataForm.contactTel}}</span>
        </el-form-item>
        <el-form-item label="联 系 地 址:">
          <el-input v-if="dialogStatus=='checkPending'" v-model="dataForm.contactAddress" clearable maxlength="50" />
          <span v-else class="form-span">{{dataForm.contactTel}}</span>
        </el-form-item>
        <el-form-item label="商 户 类 型 :">
          <!-- <el-select v-if="dialogStatus=='checkPending'" v-model="dataForm.userType" clearable style="width: 200px" class="filter-item" placeholder="商户类型">
            <el-option v-for="(item, index) in levelDic" :key="item" :label="item" :value="index" />
          </el-select> -->
          <span class="form-span">{{levelDic[dataForm.userType]}}</span>
        </el-form-item>
        <el-form-item v-if="dataForm.companyLogo" label="公司logo">
          <viewer >
            <img :src="dataForm.companyLogo" width="100">
          </viewer>
        </el-form-item>
        <!-- <el-form-item v-if="dataForm.userType==99" label="经营药材范围:">
          <span clearable class="form-span" width="100">{{accordingHerbList}}</span>
          <el-button v-if="!dataForm.approveStatus==1||!dataForm.approveStatus==2" type="primary" size="mini" @click="updateHerbDialog()" style="margin-left:10px;float:right;">修改</el-button>
        </el-form-item> -->
        <!-- <el-form-item v-if="dataForm.adminUsername" label="登 录 账 号 :">
          <span class="form-span">{{dataForm.adminUsername}}</span>
        </el-form-item> -->
        <!-- <el-form-item v-if="dataForm.adminPassword" label="登 录 密 码 :">
          <span class="form-span">{{dataForm.adminPassword}}</span>
        </el-form-item> -->

        <el-form-item v-if="dataForm.certificatesImages" label="资质证书">
          <viewer v-for="certificatesImage in dataForm.certificatesImages" :key="certificatesImage" >
            <img :src="certificatesImage" width="100">
          </viewer>  
        </el-form-item>

        <el-form-item v-if="dataForm.idCard1Url" label="身份证正面图片">
          <viewer >
            <img :src="dataForm.idCard1Url" width="100">
          </viewer>
        </el-form-item>

        <el-form-item v-if="dataForm.idCard1Url" label="身份证反面图片">
          <viewer >
            <img :src="dataForm.idCard2Url" width="100">
          </viewer> 
        </el-form-item>
        <!-- <el-form-item v-if="dataForm.userType!=0" label="管理员角色" prop="adminRoleIds">
          <el-select v-if="dialogStatus!='checkPending'" v-model="dataForm.adminRoleIds" multiple placeholder="请选择" :disabled="true" >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select v-else v-model="dataForm.adminRoleIds" multiple placeholder="请选择"  >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        
        <el-form-item label="审 核 意 见 :" prop="approveRemark">
          <textarea style="width: 500px;height: 70px;" v-if="dialogStatus!='checkPending'" v-model="dataForm.approveRemark" maxlength="100" placeholder="审 核 意 见" readonly />
          <textarea style="width: 500px;height: 70px;" v-else v-model="dataForm.approveRemark" maxlength="100" placeholder="审 核 意 见"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!dataForm.approveStatus==1||!dataForm.approveStatus==2" @click="throughData" :loading="throughLoading">通过</el-button>
        <el-button type="danger" v-if="!dataForm.approveStatus==1||!dataForm.approveStatus==2" @click="rejectedData" :loading="stepLoading">驳回</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
    
    <!-- <el-dialog title="修改经营药材范围" :visible.sync="herbFormVisible" width="670px">
      <template>
        <el-transfer
          filterable
          filter-placeholder="请输入名称"
          :button-texts="['移除', '添加']"
          :titles="['未选择', '已选择']"
          v-model="transferData"
          :data="this.allTransferData">
        </el-transfer>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateHerb()">确定</el-button>
        <el-button @click="herbFormVisible = false">取消</el-button>
      </div>
    </el-dialog> -->

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

  </div>
</template>

<style>
  .form-span{
    width: 100%;
  }
  .table-expand {
    font-size: 0;
    padding-left: 60px;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
  .herb-detail-box img {
    width: 100%;
  }
</style>

<script>
import { queryRoleIds,rejectedUserAudit,fetchHerbList,fetchList, approvalUserAudit,fetchAllHerbList} from '@/api/userAudit'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'
import { roleOptions } from '@/api/role'

export default {
  name: 'userAuditList',
  components: { BackToTop, Pagination },
  data() {
    return {
      thumbnail,
      toPreview,
      total: 0,
      stepLoading: false,
      throughLoading: false,
      listLoading: true,
      roleOptions: [],
      // all: 'default',
      waiting: 'primary',
      approval: 'default',
      rejected: 'default',
      listQuery: {
        page: 1,
        limit: 20,
        userType: undefined,
        approveStatus: 0,
        companyName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        companyName: undefined,
        adminUsername: undefined,
        adminPassword: undefined,
        adminRoleIds: undefined,
        approveRemark: undefined,
      },
      rules: {
        approveRemark: [{  required: true, message: '审核意见不能为空', trigger: 'blur' }],
      },
      list:[],
      accordingHerbList:'',
      herbList:[],
      allHerbList:[],
      transferData:[],
      allTransferData:[],
      dialogStatus: '',
      dialogFormVisible: false,
      herbFormVisible: false,
      levelDic: ['个人', '车商', '经销商'],
      statusDic: ['待审核', '批准', '驳回'],
      textMap: {
        rejected: '已驳回',
        approval: '已批准',
        checkPending: '待审核'
      },
      filterMethod(query, item) {
          return item;
        }
    }
  },
  created() {
    Promise.all([
      this.getList(),
      this.getRole(),
      this.getHerb()
    ])
  },
  mounted() {
    // 绑定enter事件
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  methods: {
    enterKey(event) {
      if(event.key=='Enter'){
        this.handleFilter()
      }
    },
    enterKeyupDestroyed() {
        document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() {
        document.addEventListener("keyup", this.enterKey);
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.list.forEach(element => {
          if(element.certificatesImage){
            element.certificatesImages=element.certificatesImage.split(',')
          }
        });
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    getHerb(){
      fetchAllHerbList().then(response => {
        this.allHerbList=response.data.data
        this.allHerbList.forEach((city, index) => {
          this.allTransferData.push({
            label: city,
            key: city
          })
        })
      })
    },
    getRole(){
      roleOptions()
      .then(response => {
        this.roleOptions = response.data.data.list
      })
    },
    handleFilter(state) {
      this.buttonChange(state)
      this.listQuery.approveStatus=state
      this.listQuery.page = 1
      this.getList()
    },
    buttonChange(state){
      this.all='default'
      this.waiting='default'
      this.approval='default'
      this.rejected='default'
      if(state=='0'){
        this.waiting='primary'
      }else if(state=='1'){
        this.approval='primary'
      }else if(state=='2'){
        this.rejected='primary'
      }else{
        this.all='primary'
      }
    },
    //弹出批准窗口
    handleThrough(row) {
        this.stepLoading=false
        this.throughLoading=false
        this.fetchHerbList(row.id)
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'checkPending'
        this.dialogFormVisible = true
        if(row.adminId){
        this.dataForm.adminRoleIds =this.queryRoleIds(row.adminId).map((t)=> Number(t))
        }else{
          this.dataForm.adminRoleIds=undefined
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
    },
    //弹出查看窗口
    handleView(row) {
      this.fetchHerbList(row.id)
        this.dataForm = Object.assign({}, row)
        if(this.dataForm.approveStatus==1){
        if(this.dataForm.adminRoleIds=='[]'){
          this.dataForm.adminRoleIds=undefined
        }else if(this.dataForm.adminRoleIds!=undefined){
          this.dataForm.adminRoleIds=this.dataForm.adminRoleIds.split(',').map((t)=> Number(t))
        }
        }
        if(this.dataForm.approveStatus==1){
          this.dialogStatus = 'approval'
        }else{
          this.dialogStatus = 'rejected'
        }
        
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
    },
    updateHerbDialog(){
      this.transferData=this.herbList
      this.herbFormVisible = true
    },
    updateHerb(){
      this.herbList=this.transferData
      console.log(this.herbList.length)
      this.accordingHerbList=''
      this.herbList.forEach(element => {
            this.accordingHerbList=this.accordingHerbList+','+element
        })
        this.accordingHerbList=this.accordingHerbList.replace(/^(\s|,)+|(\s|,)+$/g,'');
      this.herbFormVisible = false
    },
    //查询经营药材范围
    fetchHerbList(id){
      var that = this
      that.accordingHerbList=''
      that.herbList=[]
      var data={}
      data.userApproveId=id
        fetchHerbList(data).then(response => {
          console.log(response)
          that.herbList=response.data.data
           response.data.data.forEach(element => {
            that.accordingHerbList=that.accordingHerbList+','+element
        })
        that.accordingHerbList=that.accordingHerbList.replace(/^(\s|,)+|(\s|,)+$/g,'');
          }).catch(() => {
        
      })
    },
    //查询角色
    queryRoleIds(id){
      var that = this
      var data={}
      data.adminId=id
        queryRoleIds(data).then(response => {
          this.dataForm.adminRoleIds=response.data.data
          }).catch(() => {
        
      })
    },
    //批准审核
    throughData(){
      this.$refs['dataForm'].validate(valid => {
        if(this.dataForm.userType==99&&this.herbList.length==0){
          this.$message({
            type: 'warning',
            message: '经营药材范围不能为空'
          }) 
        }else if (valid) {
          this.throughLoading=true
          if(this.dataForm.adminRoleIds!=undefined){
            this.dataForm.adminRoleIds= this.dataForm.adminRoleIds.join(',')
          }
          this.$confirm('此操作将批准审核, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
            
              this.dataForm.newHerbList=this.herbList
            
              approvalUserAudit(this.dataForm)
                .then(() => {
                  this.dialogFormVisible = false
                  this.$notify.success({
                    title: '批准成功'
                  })
                    this.getList()
                })
                .catch(response => {
                  this.throughLoading=false
                  this.$notify.error({
                    title: '批准失败',
                    message: response.data.errmsg
                  })
                })
          }).catch(() => {
          this.throughLoading= false
          this.$message({
            type: 'info',
            message: '已取消批准'
          })  
        })
        }
      })
    },
    //驳回审核
    rejectedData() {
      
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.stepLoading=true
          this.dataForm.adminRoleIds= undefined
          this.$confirm('此操作将驳回审核, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
          rejectedUserAudit(this.dataForm)
            .then(() => {
              this.dialogFormVisible = false
              this.$notify.success({
                title: '驳回成功'
              })
              this.getList()
              
            })
            .catch(response => {
              this.stepLoading=false
              this.$notify.error({
                title: '驳回失败',
                message: response.data.errmsg
              })
            })
            }).catch(() => {
          this.stepLoading= false
          this.$message({
            type: 'info',
            message: '已取消驳回'
          })  
        })
        }
      })
    }
 }
}
</script>
